<?php

namespace EthanZ\LaravelExt\Models\Traits;

use EthanZ\LaravelExt\Models\GlobalScopes\UserQuery;
use EthanZ\LaravelExt\Models\Observers\AddDescription;
use EthanZ\LaravelExt\Models\Observers\AddUserId;
use EthanZ\LaravelExt\Utils\User;
use Illuminate\Database\Eloquent\Builder;

/**
 * 操作字段
 *
 * @package EthanZ\LaravelExt\Models\Traits
 */
trait OperationFields
{


    /**
     * 全局作用域
     */
    public static function bootOperationFields(): void
    {
        if (in_array('user_id', static::OPERATION_FIELDS, true)) {
            static::observe(AddUserId::class);
            static::addGlobalScope(new UserQuery);
        }

        if (in_array('description', static::OPERATION_FIELDS, true)) {
            static::observe(AddDescription::class);
        }
    }


    /**
     * 批量新增
     *
     * @param Builder $query 查询.
     * @param array   $data
     *
     * @return bool
     */
    public function scopeBatchInsert(Builder $query, array $data): bool
    {
        if (in_array('user_id', static::OPERATION_FIELDS, true)) {
            $userId = request('user_id');
            data_fill($data, '*.user_id', $userId);
        }

        if (in_array('description', static::OPERATION_FIELDS, true)) {
            $description = request('description', '');
            data_fill($data, '*.description', $description);
        }

        if ($this->timestamps) {
            $time = time();
            data_fill($data, '*.created_at', $time);
            data_fill($data, '*.updated_at', $time);
        }

        return $query->insert($data);
    }
}